<?php

namespace App\Utility;

use EasySwoole\EasySwoole\Config;

class Token{
    /**
     * 加解密
     * @param $data
     * @return string
     */
    public static function decryptWithOpenssl($data){
        $key = Config::getInstance()->getConf('ENCRYPT.key');
        $iv = Config::getInstance()->getConf('ENCRYPT.iv');
        return openssl_decrypt(base64_decode($data),"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv);
    }

    public static function encryptWithOpenssl($data){
        $key = Config::getInstance()->getConf('ENCRYPT.key');
        $iv = Config::getInstance()->getConf('ENCRYPT.iv');
        return base64_encode(openssl_encrypt($data,"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv));
    }


    /**构建会话加密函数，默认30天超时
     * @param $openid
     * @param int $exptime
     * @return string
     */
    public static function sessionEncrypt($openid, $exptime=2592000){
        $exptime = time() + $exptime;
        return self::encryptWithOpenssl($openid.'|'.$exptime);
    }

    /**
     * 验证会话token是否有效
     * @param $raw
     * @return bool
     */
    public static function sessionCheckToken($raw){
        $data = self::decryptWithOpenssl($raw);
        //如果解密不出文本返回失败
        if(!$data){
            return false;
        }
        $token = explode('|', $data);
        //如果分离出来的openid的过期时间为空 返回失败
        if(!isset($token[0]) || !isset($token[1])){
            return false;
        }
        //如果时间过期，返回失败
        if( $token[1] < time()){
            return false;
        }
        return $token[0];
    }
}
